package com.serialcommunication.controller;

import java.io.IOException;
import java.lang.Object.*;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.soap.encoding.Hex;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

public class _TwoWaySerialComm {
	
	CommPort commPort;
	
	public _TwoWaySerialComm() {
		super();
	}

	void connect(String portName) throws Exception {
		CommPortIdentifier portIdentifier = CommPortIdentifier
				.getPortIdentifier(portName);
		if (portIdentifier.isCurrentlyOwned()) {
			System.out.println("Error: Port is currently in use");
		} else {
			commPort = portIdentifier.open(this.getClass().getName(),
					2000);
			

			if (commPort instanceof SerialPort) {
				SerialPort serialPort = (SerialPort) commPort;
				serialPort.setSerialPortParams(115200, SerialPort.DATABITS_8,
						SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

				InputStream in = serialPort.getInputStream();
				OutputStream out = serialPort.getOutputStream();

//				(new Thread(new SerialReader(in))).start();
				(new Thread(new SerialWriter(out, commPort))).start();

			} else {
				System.out
						.println("Error: Only serial ports are handled by this example.");
			}
		}
	}

	/** */
	public static class SerialReader implements Runnable {
		InputStream in;

		public SerialReader(InputStream in) {
			this.in = in;
		}

		public void run() {
			byte[] buffer = new byte[1024];
			int len = -1;
			try {
				while ((len = this.in.read(buffer)) > -1) {
					System.out.print(new String(buffer, 0, len));
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/** */
	public static class SerialWriter implements Runnable {
		OutputStream out;
		CommPort commPort;

		public SerialWriter(OutputStream out, CommPort port) {
			this.out = out;
			commPort = port;
		}

		public void run() {
			try {
//				String hex = "1F";
				Hex hex = new Hex("FA");
				
//				Integer[] test = new Integer[4];
//				test[0] = 0x31;
//				test[1] = 0x31;
//				test[2] = 0x31;
//				test[3] = 0x31;
//				byte[] data = new byte[] {(byte)hex};
			
				
//				for (int i = 0; i<test.length; i++) {
//					this.out.write(test[i]);
//				}
				byte[] b = hex.getBytes();
				out.write(b);
				commPort.close();
				
				System.out.println("writing done");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		try {
			(new _TwoWaySerialComm()).connect("COM21");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
